import { ElMessageBox } from 'element-plus'
import { useLoading } from './useLoading'

/**
 * @description 操作单条数据信息 (二次确认【删除、禁用、启用、重置密码】)
 * @param {Function} apikey 操作数据接口的api消息方法 (必传)
 * @param {object} params 携带的操作数据参数 {id,params} (必传)
 * @param {string} message 提示信息 (必传)
 * @param {string} cb 回调函数
 * @param cb.onSuccess 成功回调
 * @param cb.onCancel 取消回调
 */

export function useConfirm(apikey: string, params: any = {}, message: string, { onSuccess = null, onCancel = null } = {}) {
  const loading = useLoading()
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(`是否${message}?`, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }).then(async () => {
      loading.open()
      const { success } = await useRequest(apikey, params)
      if (success) {
        resolve(success)
        onSuccess && onSuccess()
      }
      else {
        reject(new Error('操作失败'))
      }
      loading.close()
    }).catch(() => {
      onCancel && onCancel()
    }).finally(() => {
      loading.close()
    })
  })
}
